import React, {useContext, useRef, useEffect} from 'react';
import {
  View,
  PanResponder,
  Alert,
  Platform,
  ScrollView,
  FlatList,
} from 'react-native';
import dayjs from 'dayjs';
import Toast from 'react-native-root-toast';
import {useNavigation} from '@react-navigation/native';
import {useDebounceEffect, useMount, useUnmount, useSafeState} from 'ahooks';
import {Text, Button, Input, Dialog, ListItem, Avatar} from '@rneui/themed';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {useSelector, useDispatch} from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import GlobalContext from '@/GlobalContext';
import ImagePicker from 'react-native-image-crop-picker';
import fileExtension from 'file-extension';
import {ApiHost, OssHost} from '@/config/common';
import {setKeyGetAccountInfo} from '@/store';
import DocumentPicker from 'react-native-document-picker';

import RNFS from 'react-native-fs';
import RNFetchBlob from 'react-native-blob-util';
import {round} from 'lodash';
import {Dirs, FileSystem} from 'react-native-file-access';

import getFilesInfoSystem from '../getFilesInfoSystem';
import getFilesInfoMongoDb from '../getFilesInfoMongoDb';
export default () => {
  const {localMongoDbFileSystem} = useContext(GlobalContext);

  return (
    <>
      <Button
        title="InsertSDCard"
        onPress={async () => {
          const start = dayjs();
          const pPath = Dirs.SDCardDir;
          const db = localMongoDbFileSystem;
          const systemFiles = await getFilesInfoSystem({pPath});
          const mongodbFiles = await getFilesInfoMongoDb({pPath, db});

          const sysMap = new Map(systemFiles.map(item => [item.path, item]));
          const mogMap = new Map(mongodbFiles.map(item => [item.path, item]));

          //系统已删除的文件
          const hasRemoveFiles = [];
          mongodbFiles.forEach(mgItem => {
            const hasItem = sysMap.get(mgItem.path);
            if (!hasItem) {
              hasRemoveFiles.push(mgItem);
            }
          });
          //系统新增的文件
          const newAddFiles = [];
          systemFiles.forEach(sysItem => {
            const hasItem = mogMap.get(sysItem.path);
            if (!hasItem) {
              const newItem = {
                ...sysItem,
              };
              if (newItem.isDir) {
                newItem.updateDirStatus = 'wait';
              }
              newAddFiles.push(newItem);
            }
          });
          try {
            await db.insert(newAddFiles);
          } catch (e) {
            console.log('新增.异常', e.message);
          }

          //系统已修改的文件
          const newUpdFiles = [];
          systemFiles.forEach(sysItem => {
            const hasItem = mogMap.get(sysItem.path);
            if (hasItem && sysItem.update_dt !== hasItem.update_dt) {
              newUpdFiles.push({
                ...sysItem,
                oid: hasItem._id,
              });
            }
          });
          for (const data of new Set(newUpdFiles)) {
            try {
              const {oid, ...doc} = data;
              const newItem = {...doc};
              if (newItem.isDir) {
                newItem.updateDirStatus = 'wait';
              }

              await db.update({_id: oid}, newItem);
            } catch (e) {
              console.log('新增.异常', e.message);
            }
          }

          console.log(systemFiles[0]);
          console.log('hasRemoveFiles', hasRemoveFiles);
          console.log('newAddFiles', newAddFiles);
          console.log('newUpdFiles', newUpdFiles);

          const dirStat = await FileSystem.statDir('/sdcard/电影B');
          console.log('dirStat', dirStat);

          const end = dayjs();
          console.log(
            '  end:',
            end.format(),
            'use',
            end.diff(start, 'ms'),
            'ms',
          );
        }}
        containerStyle={{
          margin: 10,
        }}
      />
    </>
  );
};
